package com.zz.hhbl.ui.navigation

import android.graphics.Bitmap
import android.graphics.Canvas
import android.location.Location
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.activity.viewModels
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.Poi
import com.amap.api.navi.AmapNaviPage
import com.amap.api.navi.AmapNaviParams
import com.amap.api.navi.AmapNaviType
import com.amap.api.navi.AmapPageType
import com.zz.framework.core.base.BaseActivity
import com.zz.framework.core.ext.convertToBitmap
import com.zz.framework.core.ext.finish
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.toBitmap
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.toast.ToastUtils
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.widget.LinearLayoutRadioGroup
import com.zz.framework.widget.LinearLayoutRadioGroup.OnCheckedChangeListener
import com.zz.hhbl.R
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.ActivityWalkNavigationBinding
import com.zz.hhbl.databinding.MarkerMyLocationBinding
import com.zz.hhbl.databinding.SpotMarkerBinding
import com.zz.hhbl.entity.SpotPointEntity
import com.zz.hhbl.ui.CommonViewModel
import com.zz.hhbl.utils.DialogUtils
import dagger.hilt.android.AndroidEntryPoint


/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/7 12:57.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 * https://lbs.amap.com/api/android-sdk/guide/create-map/mylocation
 */
@AndroidEntryPoint
class WalkNavigationActivity : BaseActivity() {
    private val viewModel: CommonViewModel by viewModels()
    private val binding: ActivityWalkNavigationBinding by viewBinding()
    var location: Location? = null
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding.apply {
            btnBack.text = Strings.返回.toLanguage()
            btnBack.onClick {
                finish()
            }
            mapView.onCreate(savedInstanceState) // 此方法必须重写
            val aMap: AMap = mapView.map
            aMap.apply {
                this.setMapLanguage(if (TextUtils.equals(LanguageManager.currentLangCode,"en")) AMap.ENGLISH else AMap.CHINESE)
                this.isTrafficEnabled = false // 显示实时交通状况
                //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
                this.mapType = AMap.MAP_TYPE_NORMAL
                // 卫星地图模式
                this.myLocationStyle = MyLocationStyle().also {
                    it.myLocationIcon(BitmapDescriptorFactory.fromView(MarkerMyLocationBinding.inflate(layoutInflater).root))
                    it.showMyLocation(TextUtils.equals(LanguageManager.currentLangCode,"en").not()) //蓝色圈圈
                    it.interval(5000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
                    it.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) //连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
                }
                /// 设置地图的缩放级别
                val zoomLevel = 17f; // 缩放级别范围通常是 3.0f - 20.0f
                moveCamera(CameraUpdateFactory.zoomTo(zoomLevel))
                //启动定位
                this.isMyLocationEnabled = true
                this.uiSettings.apply {
                    this.isMyLocationButtonEnabled = false
                    this.isZoomControlsEnabled = false
                    this.setLogoBottomMargin(-100)
                }
                setOnMyLocationChangeListener { location ->
                    location?.let {
                        if (TextUtils.equals(LanguageManager.currentLangCode,"en")) {
                             addMyMarks(location)
                        }
                    }
                    this@WalkNavigationActivity.location = location
                }
                addOnMarkerClickListener { marker ->
                    val title: String = marker.title
                    val snippet: String = marker.snippet
                    val position = marker.position
                    DialogUtils.showTwoButtonDialog(
                        this@WalkNavigationActivity,
                        Strings.提示.toLanguage(),
                        "${Strings.是否导航到.toLanguage()}$title ?",
                        rightText = Strings.确定.toLanguage(),
                        rightListener = {
                            navigateTo(Poi(title, position, null))
                        })
                    true
                }
                GlobalCache.getSpotInfo().getLatLngBounds()?.let {
                    //设置缩放范围
                    //西南，东北
                    setMapStatusLimits(it)
                }
            }
            clLocation.onClick {
                // 开启定位并显示定位蓝点
                aMap.isMyLocationEnabled = true
                // 移动地图到当前位置
                aMap.myLocation?.let {
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.latitude, it.longitude), 15f))
                }
            }
            radioButton1.setText(Strings.景点.toLanguage())
            radioButton2.setText(Strings.卫生间.toLanguage())
            radioButton3.setText(Strings.商铺.toLanguage())
            radioButton4.setText(Strings.停车场.toLanguage())
            radioButton5.setText(Strings.游客中心.toLanguage())
            radioButton6.setText(Strings.景区大门.toLanguage())
            radioGroup.setOnCheckedChangeListener(listener = object : OnCheckedChangeListener {
                override fun onCheckedChanged(group: LinearLayoutRadioGroup, checkedId: Int) {
                    when (checkedId) {
                        //景点
                        R.id.radioButton1 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "01") }?.let {
                                addMarks(it)
                            }
                        }
                        //卫生间
                        R.id.radioButton2 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "02") }?.let {
                                addMarks(it)
                            }
                        }
                        //商铺
                        R.id.radioButton3 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "03") }?.let {
                                addMarks(it)
                            }
                        }
                        //停车场
                        R.id.radioButton4 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "04") }?.let {
                                addMarks(it)
                            }
                        }
                        //游客中心
                        R.id.radioButton5 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "05") }?.let {
                                addMarks(it)
                            }
                        }
                        //景区大门
                        R.id.radioButton6 -> {
                            viewModel.spotPointMarksLiveData.value?.filter { TextUtils.equals(it.type, "06") }?.let {
                                addMarks(it)
                            }
                        }
                    }
                }
            })
        }
        showProgress()
        viewModel.getMapSpotPointMarks()
    }

    override fun initObserver() {
        viewModel.spotPointMarksLiveData.observe(this) {
            dismissProgress()
            addMarks(it)
        }
    }

    /**
     * 导航
     * @param to Poi
     */
    fun navigateTo(to: Poi) {
        //构建导航组件配置类，没有传入起点，所以起点默认为 “我的位置”
        val params = AmapNaviParams(null, emptyList(), to, AmapNaviType.WALK, AmapPageType.NAVI)
        //启动导航组件
        AmapNaviPage.getInstance().showRouteActivity(applicationContext, params, null)
    }

    fun addMarks(list: List<SpotPointEntity>) {
        //binding.mapView.map.clear()
        clearMarkers()
        binding.mapView.postDelayed({
            list.forEach { point ->
                val markerView = createMarkerView(point)
                val bitmap = markerView.convertToBitmap()
                val options = MarkerOptions()
                    .position(point.getLatLng())
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                    .title(point.name.orEmpty())
                    .snippet(point.remark.orEmpty())
                val marker = binding.mapView.map.addMarker(options)
                marker.`object` = point
            }
        }, 500)
        zoomToShowAllPoints(list.map { it.getLatLng() }?.toMutableList())
    }

    fun addMyMarks(location: Location) {
        val latLng = LatLng(location.latitude, location.longitude)
        binding.mapView.postDelayed({
            val bitmap = BitmapDescriptorFactory.fromView(MarkerMyLocationBinding.inflate(layoutInflater).root)
            val options = MarkerOptions()
                .position(latLng)
                .icon(bitmap)
            clearMyMarkers()
            val marker = binding.mapView.map.addMarker(options)
            marker.`object` = "myMarker"
        }, 10)
    }


    private fun clearMarkers() {
        // 获取地图上所有Marker
        val mapScreenMarkers = binding.mapView.map.mapScreenMarkers;
        mapScreenMarkers.forEach { marker ->
            if (marker.`object` is SpotPointEntity) {
                marker.remove()
            }
        }
        binding.mapView.invalidate()
    }

    private fun clearMyMarkers() {
        // 获取地图上所有我的Marker
        val mapScreenMarkers = binding.mapView.map.mapScreenMarkers;
        mapScreenMarkers.forEach { marker ->
            if (marker.`object` is String) {
                marker.remove()
            }
        }
        binding.mapView.invalidate()
    }


    private fun createMarkerView(point: SpotPointEntity): View {
        val markerBinding = SpotMarkerBinding.inflate(LayoutInflater.from(this))
        markerBinding.tvTitle.text = point.name
        markerBinding.root.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )
        markerBinding.ivIcon.setImageResource(point.getIconRes())
        return markerBinding.root
    }


    private fun zoomToShowAllPoints(points: MutableList<LatLng>?) {
        if (points.isNullOrEmpty()) {
            return
        }
        location?.let {
            points.add(LatLng(it.latitude, it.longitude))
        }
        // 计算边界范围
        val builder = LatLngBounds.Builder()
        for (point in points) {
            builder.include(point)
        }
        val bounds = builder.build()
        // 设置地图视野
        val padding = 100 // 边界与地图边缘的间距，单位为像素
        binding.mapView.map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding))
    }

    override fun onDestroy() {
        super.onDestroy()
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        binding.mapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        binding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        binding.mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState!!)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        binding.mapView.onSaveInstanceState(outState)
    }
}